package com.xxl.job.admin.core.util.alarm;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author chenlinqing
 * @description:
 * @date: 2025/8/25 11:25
 */
@Component
public class QiYeWechatAlarmUtil {
    private static Logger logger = LoggerFactory.getLogger(QiYeWechatAlarmUtil.class);
    private static ObjectMapper objectMapper = new ObjectMapper();

    public void sendMessage(String title, String alarmTo, String jobHandler, String jobDesc, String errorMsg) {
        try {
            Map<String, Object> map = MapUtil.newHashMap();
            QiYeWechatMessageContent messageContent = new QiYeWechatMessageContent();
            String content = generateContent(jobHandler, jobDesc, errorMsg);
            messageContent.setContent(StrUtil.sub(content, 0, 4096));
            map.put("msgtype", "markdown");
            map.put("markdown", messageContent);
            HttpRequest post = HttpUtil.createPost(alarmTo);
            HttpRequest request = post.body(objectMapper.writeValueAsString(map), ContentType.JSON.toString());
            HttpResponse execute = request.execute();
            logger.info("QiYeWechat send message result:{}", execute.body());
            if (!execute.isOk()) {
                throw new RuntimeException(execute.body());
            }
        } catch (Exception e) {
            logger.error("QiYeWechat send message error", e);
            throw new RuntimeException(e.getMessage());
        }
    }


    private String generateContent(String jobHandler, String jobDesc, String errorMsg) {
        return "定时任务handler：%s，\n 定时任务描述：%s \n 执行报错。错误日志如下：\n %s".formatted(jobHandler, jobDesc, errorMsg);
    }


    private static class QiYeWechatMessageContent {
        /**
         * markdown内容，最长不超过4096个字节，必须是utf8编码
         */
        private String content;

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}
